#!/usr/bin/env bash

cd /tmp

# Stuff
echo "export LANG=en_US.UTF-8;export LC_ALL=en_US.UTF-8;export LC_CTYPE=en_US.UTF-8" >> /etc/bash.bashrc
cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

# set swap memory
dd if=/dev/zero of=/var/swap.1 bs=1M count=2048
mkswap /var/swap.1
swapon /var/swap.1

# replace source mirror
cp /vagrant/install/source.list /etc/apt/sources.list
apt-get update
apt-get -y upgrade

apt-get install -y gcc g++ git autoconf re2c libxml2-dev libssl-dev pkg-config libcurl4-gnutls-dev libreadline-dev ruby python gems python-pip exuberant-ctags gem nginx python-dev libmcrypt-dev

# Cmake
mkdir -p /tmp/cmake
cd /tmp/cmake
wget https://cmake.org/files/v3.7/cmake-3.7.2-Linux-x86_64.tar.gz
tar xvzf cmake-3.7.2-Linux-x86_64.tar.gz
CMAKE_TARGET=(bin  doc  man  share)
for i in ${CMAKE_TARGET[@]}
do
    cp -r cmake-3.7.2-Linux-x86_64/$i/* /usr/local/$i
done
cd /tmp

# Install Vim
mkdir -p /tmp/vim
cd /tmp/vim
wget ftp://ftp.vim.org/pub/vim/unix/vim-8.0.tar.bz2
tar xvjf vim-8.0.tar.bz2
cd vim80

./configure --with-features=huge \
    --enable-multibyte \
    --enable-pythoninterp=yes \
    --with-python-config-dir=/usr/lib/python2.7/config

make && make install

cd /tmp
rm -rf /tmp/vim

# install basic ruby package
gem sources -c
gem sources -u
gem sources -r http://rubygems.org/
gem sources -r https://rubygems.org/
gem sources --add https://gems.ruby-china.org/
gem sources -c
gem sources -u

# gem install rails

# install nginx

cp /vagrant/install/nginx/sites-enabled/default /etc/nginx/sites-enabled/default
nginx -s stop # default shutdown

# Install Mysql
debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password qwe123'
debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password qwe123'
apt-get -y install mysql-server-5.6
echo "alias mysql='mysql -uroot -pqwe123'" >> /etc/bash.bashrc

# auto start
update-rc.d -f mysql defaults

# Ending

# Run other script
useradd -d /home/work -m work
su - work -s /bin/bash /vagrant/auto-vagrant-poststrap.sh

apt-get -y autoremove
apt-get -y clean
cd /var/
rm -rf cache/* backups/* tmp/*
rm -rf /tmp/*

echo "Minimizing disk image..."
dd if=/dev/zero of=/EMPTY bs=1M
rm -f /EMPTY
sync
